#!/usr/bin/env python
# -*- coding:UTF-8 -*-
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse, JsonResponse
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django import forms
from app_JDGL.models import Person
from app_JDGL.models import Company

import sys
import traceback
import logging
import cgi, cgitb
from os import environ
from string import strip, split
import datetime, time
import MySQLdb
import base64
import socket
from struct import *
import ctypes
import json
import hashlib
import os

import web_XZDQ_V1_0.MySQLDB as MySQLDB
import web_XZDQ_V1_0.PowerID as PowerID


# Create your views here.

# 装饰器html 权限验证 系统管理id=8
def auth(func):
    def inner(request):
        # 权限验证
        menudate = []
        try:
            userid = request.COOKIES['userid']
            row0 = MySQLDB.SelectMySql("SELECT role_id FROM t_sys_user WHERE user_id = %s AND status = 1;" % userid)
            # if row0[0][1] == 0:
            #    response = render(request,'login.html', {})
            #    return response
            row1 = MySQLDB.SelectMySql("SELECT menu_id FROM t_role_menu WHERE role_id = %s;" % row0[0][0])
            for i in range(len(row1)):
                menudate.append(row1[i][0])
        except:
            pass
        if 8 not in menudate:
            # return HttpResponseRedirect('/')
            response = render(request, 'login.html', {})
            return response
        # 多用户登录验证
        md5str = request.COOKIES['loginmd5']
        row0 = MySQLDB.SelectMySql("SELECT user_id FROM t_sys_user WHERE valid_md5 = '%s';" % md5str)
        try:
            if str(row0[0][0]) == userid:
                pass
            else:
                # return HttpResponseRedirect('/')
                response = render(request, 'login.html', {})
                return response
        except:
            # return HttpResponseRedirect('/')
            response = render(request, 'login.html', {})
            return response
        return func(request)

    return inner


# 装饰器json 权限验证 系统管理id=8
def authjson(func):
    def jnner(request):
        # 权限验证
        menudate = []
        try:
            userid = request.COOKIES['userid']
            row0 = MySQLDB.SelectMySql("SELECT role_id FROM t_sys_user WHERE user_id = %s AND status = 1;" % userid)
            row1 = MySQLDB.SelectMySql("SELECT menu_id FROM t_role_menu WHERE role_id = %s;" % row0[0][0])
            for i in range(len(row1)):
                menudate.append(row1[i][0])
        except:
            data = {
                "status": 0,
                "message": u"登录超时，请重新登陆!",
                "data": []
            }
            jsonstr = json.dumps(data)
            return HttpResponse(jsonstr, content_type="application/json")
        if 8 not in menudate:
            data = {
                "status": 0,
                "message": u"权限不够！",
                "data": []
            }
            jsonstr = json.dumps(data)
            return HttpResponse(jsonstr, content_type="application/json")
        # 多用户登录验证
        md5str = request.COOKIES['loginmd5']
        row0 = MySQLDB.SelectMySql("SELECT user_id FROM t_sys_user WHERE valid_md5 = '%s';" % md5str)
        try:
            if str(row0[0][0]) == userid:
                pass
            else:
                data = {
                    "status": 0,
                    "message": u"该账号在其他地方登录",
                    "data": []
                }
                jsonstr = json.dumps(data)
                return HttpResponse(jsonstr, content_type="application/json")
        except:
            data = {
                "status": 0,
                "message": u"其他错误",
                "data": []
            }
            jsonstr = json.dumps(data)
            return HttpResponse(jsonstr, content_type="application/json")
        return func(request)

    return jnner


# 功能：html界面跳转方法
# 输入参数：request
# 返回参数：response/login.html
# 部门管理首页 页面
@auth
def department(request):
    response = render(request, 'XTGL/XTGL_BMGL_index.html', {})
    return response


# 部门管理新增 页面
@auth
def XTGL_BMGL_ADD(request):
    data = []
    try:
        row1 = MySQLDB.SelectMySql("SELECT organize_id,name from t_sys_organize where status=1 and category=1;")
        if len(row1) > 0:
            key = ["parentID", "parent_name"]
            for i in range(len(row1)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row1[i][j]
                data.append(info)
    except Exception as e:
        pass
    response = render(request, 'XTGL/XTGL_BMGL_ADD.html', {"data": data})
    return response


# 部门管理修改 页面
@auth
def XTGL_BMGL_MODIFY(request):
    OrganizeID = request.GET['organizeID']
    orint = int(OrganizeID)
    row = MySQLDB.SelectMySql(
        "SELECT organize_id,name,parent_id,parent_name,address,manager,tel,description from t_sys_organize where organize_id=%s;" % orint)
    data = []
    try:
        row1 = MySQLDB.SelectMySql("SELECT organize_id,name from t_sys_organize where status=1 and category=1;")
        if len(row1) > 0:
            key = ["parentID", "parent_name"]
            for i in range(len(row1)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row1[i][j]
                data.append(info)
    except Exception as e:
        pass
    try:
        if len(row) > 0:
            name = row[0][1]
            parent_id = row[0][2]
            parent_name = row[0][3]
            address = row[0][4]
            manager = row[0][5]
            tel = row[0][6]
            description = row[0][7]
        else:
            name = "None"
            parent_id = 0
            parent_name = "None"
            address = "None"
            manager = "None"
            tel = "None"
            description = "None"
    except:
        name = "None"
        parent_id = 0
        parent_name = "None"
        address = "None"
        manager = "None"
        tel = "None"
        description = "None"
    response = render(request, 'XTGL/XTGL_BMGL_MODIFY.html',
                      {"organize_id": orint, "name": name, "parent_id": parent_id, "parent_name": parent_name,
                       "address": address, "manager": manager, "tel": tel, "description": description, "data": data})
    return response


# 角色管理首页 页面
@auth
def department_1(request):
    response = render(request, 'XTGL/XTGL_JSGL_index.html', {})  # 角色管理首页
    return response


# 角色管理新增 页面
@auth
def XTGL_JSGL_ADD(request):
    response = render(request, 'XTGL/XTGL_JSGL_ADD.html', {})
    return response


# 角色管理修改
def XTGL_JSGL_MODIFY(request):
    role_id = request.GET['role_id']
    try:
        row = MySQLDB.SelectMySql("SELECT name,description FROM t_sys_role where role_id='%s';" % role_id)
        name = row[0][0]
        description = row[0][1]
    except Exception as e:
        name = "None"
        description = "None"
    response = render(request, 'XTGL/XTGL_JSGL_MODIFY.html',
                      {"role_id": role_id, "name": name, "description": description})
    return response


# 角色管理配置 页面
@auth
def XTGL_JSGL_CONFIGURE(request):
    xrole_id = request.GET['role_id']
    role_id = int(xrole_id)
    try:
        row = MySQLDB.SelectMySql("SELECT name FROM t_sys_role where role_id=%s;" % role_id)
        name = row[0][0]
    except Exception as e:
        name = "None"
    data = []
    try:
        row = MySQLDB.SelectMySql("SELECT menu_id,menu_name FROM t_sys_menu WHERE type=0 order by orderby;")
        for i in range(len(row)):
            info = {}
            info["menu_id"] = row[i][0]
            info["menu_name"] = row[i][1]
            data.append(info)
    except Exception as e:
        pass
    response = render(request, 'XTGL/XTGL_JSGL_CONFIGURE.html',
                      {"role_id": role_id, "name": name, "nameJS": json.dumps(role_id), "data": data})
    return response


# 用户管理首页 页面
@auth
def department_2(request):
    response = render(request, 'XTGL/XTGL_YHGL_index.html', {})
    return response


# 用户管理新增 页面
@auth
def XTGL_YHGL_ADD(request):
    # 角色列表
    try:
        row = MySQLDB.SelectMySql("SELECT role_id,name from t_sys_role where status=1;")
        jsalist = []
        if len(row) > 0:
            key = ["role_id", "name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                jsalist.append(info)
    except Exception as e:
        jsalist = []
    # 公司/部门列表
    try:
        row = MySQLDB.SelectMySql("SELECT organize_id,name FROM t_sys_organize where status=1 and category=1;")
        gsalist = []
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["organize_id"] = row[i][0]
                info["name"] = row[i][1]
                bmrow = MySQLDB.SelectMySql(
                    "SELECT organize_id,name FROM t_sys_organize where status=1 and category=2 and parent_id=%s;" %
                    row[i][0])
                bmdata = []
                try:
                    for i in range(len(bmrow)):
                        infodata = {}
                        infodata["organize_id"] = bmrow[i][0]
                        infodata["name"] = bmrow[i][1]
                        bmdata.append(infodata)
                except:
                    pass
                info["department"] = bmdata
                gsalist.append(info)
    except Exception as e:
        gsalist = []
    response = render(request, 'XTGL/XTGL_YHGL_ADD.html', {"jsalist": jsalist, "gsalist": gsalist})
    return response


# 用户管理修改 页面
@auth
def XTGL_YHGL_MODIFY(request):
    user_id = request.GET['user_id']  # 获取用户ID
    # 获取某个用户id的信息
    try:
        # row = MySQLDB.SelectMySql("SELECT a.user_id,a.login_name,a.password,a.sex,a.real_name,date_format(a.birthday,'%Y-%m-%d') as date,a.organize_id,a.organize_name,a.dept_name,a.duty_name,a.role_id,b.name as roleName,a.mobile,a.email from t_sys_user a inner join t_sys_role b on a.role_id = b.role_id where a.status=1 and a.user_id='%s';"%(user_id))
        row = MySQLDB.SelectMySql(
            "SELECT a.description,a.user_id,a.login_name,a.sex,a.real_name,date_format(a.birthday,'%%Y-%%m-%%d') as date,a.organize_id,a.organize_name,a.dept_name,a.duty_name,a.role_id,b.name as roleName,a.mobile,a.email from t_sys_user a inner join t_sys_role b on a.role_id = b.role_id where a.status=1 and a.user_id='%s';" % (
                user_id))
        data = []
        if len(row) > 0:
            # key = ["user_id","login_name","password","sex","real_name","birthday","organize_id","organize_name","dept_name","duty_name","role_id","roleName","mobile","email"]
            key = ["description", "user_id", "login_name", "sex", "real_name", "birthday", "organize_id",
                   "organize_name", "dept_name", "duty_name", "role_id", "roleName", "mobile", "email"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                data.append(info)
    except Exception as e:
        pass
    # 角色列表
    try:
        row = MySQLDB.SelectMySql("SELECT role_id,name from t_sys_role where status=1;")
        jsalist = []
        if len(row) > 0:
            key = ["role_id", "name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                jsalist.append(info)
    except Exception as e:
        jsalist = []
    # 公司/部门列表
    try:
        row = MySQLDB.SelectMySql("SELECT organize_id,name FROM t_sys_organize where status=1 and category=1;")
        gsalist = []
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["organize_id"] = row[i][0]
                info["name"] = row[i][1]
                bmrow = MySQLDB.SelectMySql(
                    "SELECT organize_id,name FROM t_sys_organize where status=1 and category=2 and parent_id=%s;" %
                    row[i][0])
                bmdata = []
                try:
                    for i in range(len(bmrow)):
                        infodata = {}
                        infodata["organize_id"] = bmrow[i][0]
                        infodata["name"] = bmrow[i][1]
                        bmdata.append(infodata)
                except:
                    pass
                info["department"] = bmdata
                gsalist.append(info)
    except Exception as e:
        gsalist = []
    response = render(request, 'XTGL/XTGL_YHGL_MODIFY.html', {"data": data, "jsalist": jsalist, "gsalist": gsalist})
    return response


# 个人中心首页 页面
@auth
def department_3(request):
    user_id = request.COOKIES["userid"]
    uid = int(user_id)
    try:
        row = MySQLDB.SelectMySql(
            "select user_id,real_name,sex,birthday,organize_name,duty_name,mobile,email from t_sys_user where user_id=%s;" % uid)
        data = []
        if len(row) > 0:
            for i in range(len(row)):
                info = {}
                info["user_id"] = row[i][0]
                info["real_name"] = row[i][1]
                info["sex"] = row[i][2]
                ks = row[i][3]
                info["birthday"] = ks.strftime("%Y-%m-%d")
                info["organize_name"] = row[i][4]
                info["duty_name"] = row[i][5]
                info["mobile"] = row[i][6]
                info["email"] = row[i][7]
                data.append(info)
    except Exception as e:
        data = []
        # 读取个人信息
    response = render(request, 'XTGL/XTGL_GRZX_index.html', {"data": data})
    return response


# 个人中心密码修改 页面
@auth
def XTGL_GRZX_PAWD(request):
    response = render(request, 'XTGL/XTGL_GRZX_PAWD.html', {})
    return response


# 通通讯录首页 页面
@auth
def department_4(request):
    response = render(request, 'XTGL/XTGL_TXL_index.html', {})
    return response


######################
# 部门管理方法
######################
# 功能：获取部门信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_BMGL_1(request):
    try:
        row = MySQLDB.SelectMySql(
            "SELECT organize_id,name,parent_id,parent_name,address,manager,tel,description from t_sys_organize where status=1 and category=2;")
        alist = []
        if len(row) > 0:
            key = ["organize_id", "name", "parent_id", "parent_name", "address", "manager", "tel", "description"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                alist.append(info)
        data = {
            "status": 1,
            "message": u"查询成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：修改部门信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_BMGL_2(request):
    xOrganizeID = request.POST['organizeID']
    OrganizeID = int(xOrganizeID)
    Unitname = request.POST['unitname']
    parentid = request.POST['parent_id']
    parent_id = int(parentid)
    parent_name = request.POST['parent_name']
    Address = request.POST['address']
    Header = request.POST['header']
    Tel = request.POST['tel']
    Jobdescription = request.POST['jobdescription']
    try:
        # 通过OrganizeID查询name与修改后的Unitname对比
        row = MySQLDB.SelectMySql("SELECT name FROM t_sys_organize WHERE organize_id=%s;" % OrganizeID)
        if Unitname == row[0][0]:
            row = MySQLDB.SelectMySql(
                "SELECT name FROM t_sys_organize WHERE category=2 AND status=1 AND parent_id=%s;" % parent_id)
            namedate = []
            for i in range(len(row)):
                if Unitname != row[i][0]:
                    namedate.append(row[i][0])

            if Unitname not in namedate:
                row = MySQLDB.CommitMySql(
                    "UPDATE t_sys_organize set name = '%s',parent_id = '%s',parent_name = '%s',address = '%s',manager = '%s',tel = '%s',description = '%s' where organize_id='%s';" % (
                        Unitname, parent_id, parent_name, Address, Header, Tel, Jobdescription, OrganizeID))
                row = MySQLDB.CommitMySql(
                    "UPDATE t_sys_user set dept_name = '%s',organize_id = '%s',organize_name = '%s' where dept_id='%s';" % (
                        Unitname, parent_id, parent_name, OrganizeID))
                aa = Company.objects.get(corganize_id=OrganizeID)
                aa.cname = Unitname
                aa.cpatent_id = parent_id
                aa.cpatent_name = parent_name
                aa.caddress = Address
                aa.cmanager = Header
                aa.ctel = Tel
                aa.cdesctiption = Jobdescription
                aa.save()
                data = {
                    "status": 1,
                    "message": u"修改成功",
                    "data": []
                }
            else:
                data = {
                    "status": 0,
                    "message": u"部门名称重复",
                    "data": []
                }
        else:
            row = MySQLDB.SelectMySql(
                "SELECT name FROM t_sys_organize WHERE category=2 AND status=1 AND parent_id=%s;" % parent_id)
            namedate = []
            for i in range(len(row)):
                namedate.append(row[i][0])
            if Unitname not in namedate:
                row = MySQLDB.CommitMySql(
                    "UPDATE t_sys_organize set name = '%s',parent_id = '%s',parent_name = '%s',address = '%s',manager = '%s',tel = '%s',description = '%s' where organize_id='%s';" % (
                        Unitname, parent_id, parent_name, Address, Header, Tel, Jobdescription, OrganizeID))
                row = MySQLDB.CommitMySql(
                    "UPDATE t_sys_user set dept_name = '%s',organize_id = '%s',organize_name = '%s' where dept_id='%s';" % (
                        Unitname, parent_id, parent_name, OrganizeID))
                aa = Company.objects.get(corganize_id=OrganizeID)
                aa.cname = Unitname
                aa.cpatent_id = parent_id
                aa.cpatent_name = parent_name
                aa.caddress = Address
                aa.cmanager = Header
                aa.ctel = Tel
                aa.cdesctiption = Jobdescription
                aa.save()
                data = {
                    "status": 1,
                    "message": u"修改成功",
                    "data": []
                }
            else:
                data = {
                    "status": 0,
                    "message": u"部门名称重复",
                    "data": []
                }
                # 需获取参数：部门organizeID、部门名称、parent_id、parent_name、address、manager、tel
                # t_sys_organize表更新
                # MySQLDB.CommitMySql("UPDATE t_sys_organize set name = '%s',parent_id = '%s',parent_name = '%s',address = '%s',manager = '%s',tel = '%s',description = '%s' where organize_id='%s';"%(部门名称,parent_id,parent_name,address,manager,tel,部门organizeID))
                # t_sys_user表更新
                # MySQLDB.CommitMySql("UPDATE t_sys_user set dept_name = '%s',organize_id = '%s',organize_name = '%s' where dept_id='%s';" % (部门名称,parent_id,parent_name,部门organizeID))
                # row = MySQLDB.CommitMySql("UPDATE t_sys_organize set name = '%s',parent_name = '%s',address = '%s',manager = '%s',tel = '%s',description = '%s' where organize_id='%s';"%(Unitname,Superiorunit,Address,Header,Tel,Jobdescription,OrganizeID))
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：删除部门信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_BMGL_3(request):
    xOrganizeID = request.GET['organizeID']
    OrganizeID = int(xOrganizeID)
    try:
        row = MySQLDB.SelectMySql("SELECT * FROM t_sys_user WHERE dept_id=%s AND status=1;" % OrganizeID)
        try:
            if len(row) > 0:
                data = {
                    "status": 0,
                    "message": u"部门还有人，不能删除",
                    "data": []
                }
            else:
                row = MySQLDB.CommitMySql("UPDATE t_sys_organize set status = 0 where organize_id=%s;" % OrganizeID)
                Company.objects.get(corganize_id=OrganizeID).delete()
                data = {
                    "status": 1,
                    "message": u"删除成功",
                    "data": []
                }
        except:
            row = MySQLDB.CommitMySql("UPDATE t_sys_organize set status = 0 where organize_id=%s;" % OrganizeID)
            Company.objects.get(corganize_id=OrganizeID).delete()
            data = {
                "status": 1,
                "message": u"删除成功",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：新增部门信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_BMGL_4(request):
    Unitname = request.POST['unitname']
    Superiorunit = request.POST['superiorunit']
    Address = request.POST['address']
    Header = request.POST['header']
    Tel = request.POST['tel']
    Jobdescription = request.POST['jobdescription']
    data = {
        "status": 0,
        "message": "error",
        "data": []
    }
    # 单位名称重复性判断
    try:
        row3 = MySQLDB.SelectMySql(
            "SELECT 1 from t_sys_organize where name='%s' and status=1 and category=1;" % Superiorunit)
        try:
            flag = row3[0][0]
        except:
            flag = 0
        if flag != 1:
            row1 = MySQLDB.CommitMySql(
                "INSERT INTO t_sys_organize (status,category,name) VALUES (1,1,'%s');" % Superiorunit)
    except:
        jsonstr = json.dumps(data)
        return HttpResponse(jsonstr, content_type="application/json")
    try:
        row2 = MySQLDB.SelectMySql("SELECT organize_id from t_sys_organize where name='%s';" % Superiorunit)
        parentID = row2[0][0]
    except Exception as e:
        jsonstr = json.dumps(data)
        return HttpResponse(jsonstr, content_type="application/json")
    try:
        row3 = MySQLDB.SelectMySql(
            "SELECT 1 from t_sys_organize where name='%s' and status=1 and category=2;" % Unitname)
        try:
            flag = row3[0][0]
        except:
            flag = 0
        if flag != 1:
            row = MySQLDB.CommitMySql(
                "INSERT INTO t_sys_organize (status,name,parent_id,parent_name,address,manager,tel,description,category) VALUES (1,'%s',%s,'%s','%s','%s','%s','%s',2);" % (
                    Unitname, parentID, Superiorunit, Address, Header, Tel, Jobdescription))
            data = {
                "status": 1,
                "message": u"新增部门信息成功",
                "data": []
            }
        else:
            data = {
                "status": 0,
                "message": u"部门重复",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


######################
# 角色管理方法
######################
# 功能：获取角色信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_JSGL_1(request):
    try:
        row = MySQLDB.SelectMySql("SELECT role_id,name,description from t_sys_role where status=1;")
        alist = []
        if len(row) > 0:
            key = ["role_id", "name", "description"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                alist.append(info)
        data = {
            "status": 1,
            "message": u"查询角色信息成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：修改角色信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_JSGL_2(request):
    xrole_id = request.POST['role_id']
    role_id = int(xrole_id)
    name = request.POST['name']
    description = request.POST['description']
    try:
        row1 = MySQLDB.SelectMySql("SELECT 1 FROM `t_sys_role` where name ='%s' and status=1;" % (name))
        try:
            flag = row1[0][0]
        except:
            flag = 0
        if flag != 1:
            try:
                row = MySQLDB.CommitMySql("UPDATE t_sys_role set name = '%s',description = '%s' where role_id=%s;" % (
                    name, description, role_id))
                data = {
                    "status": 1,
                    "message": u"修改角色信息成功",
                    "data": []
                }
            except Exception as e:
                data = {
                    "status": 0,
                    "message": u"查询角色信息失败",
                    "data": []
                }
        else:
            try:
                row2 = MySQLDB.SelectMySql(
                    "SELECT 1 FROM `t_sys_role` where name ='%s' and status=1 and role_id=%s;" % (name, role_id))
                try:
                    flag2 = row2[0][0]
                except:
                    flag2 = 0
                if flag2 == 1:
                    row = MySQLDB.CommitMySql(
                        "UPDATE t_sys_role set description = '%s' where role_id=%s;" % (description, role_id))
                    data = {
                        "status": 1,
                        "message": u"修改角色信息成功",
                        "data": []
                    }
                else:
                    data = {
                        "status": 0,
                        "message": u"角色名字已存在",
                        "data": []
                    }
            except Exception as e:
                data = {
                    "status": 0,
                    "message": u"查询角色信息失败1",
                    "data": []
                }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查询是否存在角色名字失败",
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：读取系统模组信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_JSGL_3(request):
    try:
        row = MySQLDB.SelectMySql("SELECT * from t_sys_menu where status=1;")
        alist = []
        if len(row) > 0:
            key = ["menu_id", "menu_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                alist.append(info)
        data = {
            "status": 1,
            "message": u"查询系统模组菜单成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：读取角色已有权限模组信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_JSGL_4(request):
    xrole_id = request.GET['role_id']
    role_id = int(xrole_id)
    try:
        row = MySQLDB.SelectMySql(
            "SELECT a.role_id,a.name, c.menu_id, c.menu_name FROM t_sys_role a inner join t_role_menu b on a.role_id = b.role_id inner join t_sys_menu c on b.menu_id = c.menu_id where a.role_id= %s and a.status=1;" % (
                role_id))
        alist = []
        if len(row) > 0:
            key = ["role_id", "name", "menu_id", "menu_name"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                alist.append(info)
        data = {
            "status": 1,
            "message": u"查询角色已有权限成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：修改保存角色权限模组信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_JSGL_5(request):
    xrole_id = request.GET['role_id']  # POST请求获取html传过来的参数
    role_id = int(xrole_id)
    menu_id = request.GET['menu_id']
    # AddNamee = unicode(AddName).encode('utf8')
    # 将数据插入数据库

    b0 = MySQLDB.CommitMySql("delete from t_role_menu where role_id = %s;" % (role_id))
    try:
        temp = menu_id.split('|')
        count = len(temp)
        del temp[count - 1]
        for i in temp:
            b1 = MySQLDB.CommitMySql("insert into t_role_menu (role_id,menu_id) value (%s,'%s');" % (role_id, i))
        data = {
            "status": 1,
            "message": u"修改角色权限成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：新增角色信息
# 输入参数：request
# 返回参数：response
def XTGL_JSGL_6(request):
    name = request.POST['name']  # POST请求获取html传过来的参数
    description = request.POST['description']
    # 将数据插入数据库
    try:
        row1 = MySQLDB.SelectMySql("SELECT 1 FROM `t_sys_role` where name ='%s' and status=1;" % (name))
        try:
            flag = row1[0][0]
        except:
            flag = 0
        if flag != 1:
            try:
                b1 = MySQLDB.CommitMySql(
                    "INSERT INTO t_sys_role (name,description,status) VALUES ('%s', '%s',1);" % (name, description))
                data = {
                    "status": 1,
                    "message": u"新增角色信息成功",
                    "data": []
                }
            except Exception as e:
                data = {
                    "status": 0,
                    "message": u"新增角色信息失败",
                    "data": []
                }
        else:
            data = {
                "status": 0,
                "message": u"角色名字已存在",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查询是否存在角色名字失败",
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：删除角色信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_JSGL_7(request):
    xrole_id = request.GET['role_id']  # POST请求获取html传过来的参数
    role_id = int(xrole_id)
    try:
        a = MySQLDB.SelectMySql("select count(1) from t_sys_user where role_id = '%s' and status=1;" % (role_id))
        if a[0][0] == 0:
            b0 = MySQLDB.CommitMySql("update t_sys_role set status = 0 where role_id = %s;" % (role_id))
            b1 = MySQLDB.CommitMySql("delete from t_role_menu where role_id = '%s';" % (role_id))
            data = {
                "status": 1,
                "message": u"删除角色信息成功",
                "data": []
            }
        else:
            data = {
                "status": 0,
                "message": u"该角色组中还有用户！",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查询角色组中是否还有用户失败",
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


######################
# 用户管理方法
######################
# 功能：获取用户信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_YHGL_1(request):
    try:
        row = MySQLDB.SelectMySql(
            "SELECT a.user_id,a.login_name,a.password,a.sex,a.real_name,date_format(a.birthday,'%Y-%m-%d') as date,a.organize_id,a.organize_name,a.dept_name,a.duty_name,a.role_id,b.name as roleName,a.mobile,a.email from t_sys_user a inner join t_sys_role b on a.role_id = b.role_id where a.status=1;")
        alist = []
        if len(row) > 0:
            key = ["user_id", "login_name", "password", "sex", "real_name", "birthday", "organize_id", "organize_name",
                   "dept_name", "duty_name", "role_id", "roleName", "mobile", "email"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                alist.append(info)
        data = {
            "status": 1,
            "message": u"查询用户信息成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }

    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：修改用户信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_YHGL_2(request):
    user_id = request.POST['user_id']
    login_name = request.POST['login_name']  # 账号
    xrole_id = request.POST['role_id']  # 角色ID
    role_id = int(xrole_id)
    real_name = request.POST['real_name']  # 姓名
    xsex = request.POST['sex']  # 性别
    sex = int(xsex)
    birthday = request.POST['birthday']  # 生日
    xorganize_id = request.POST['organize_id']  # 单位ID
    organize_id = int(xorganize_id)
    organize_name = request.POST['organize_name']  # 单位名称
    xdept_id = request.POST['dept_id']  # 部门ID
    dept_id = int(xdept_id)
    dept_name = request.POST['dept_name']  # 部门名称
    duty_name = request.POST['duty_name']  # 职务名称
    mobile = request.POST['mobile']  # 电话
    email = request.POST['email']  # 邮箱
    description = request.POST['description']
    try:
        row1 = MySQLDB.SelectMySql("SELECT 1 FROM `t_sys_user` where login_name ='%s' and status=1;" % (login_name))
        try:
            flag = row1[0][0]
        except:
            flag = 0
        if flag != 1:
            try:
                row = MySQLDB.CommitMySql(
                    "UPDATE t_sys_user set description = '%s',login_name = '%s',sex = '%s',real_name = '%s',birthday = '%s',organize_id = '%s',organize_name = '%s',dept_id = '%s',dept_name = '%s',duty_name = '%s',role_id = '%s',mobile = '%s',email = '%s' where user_id= '%s';" % (
                        description, login_name, sex, real_name, birthday, organize_id, organize_name, dept_id,
                        dept_name,
                        duty_name, role_id, mobile, email, user_id))
                aa = Person.objects.get(puserid=user_id)
                dd = User.objects.get(last_name=aa.puser.last_name)
                dd.last_name = real_name
                dd.first_name = dept_name
                dd.email = email
                dd.username = login_name
                dd.save()
                aa.prole_id = role_id
                aa.psex = sex
                aa.pbirthday = birthday
                aa.porganize_id = organize_id
                aa.porganize_name = organize_name
                aa.pdept_id = dept_id
                aa.pdept_name = dept_name
                aa.pduty_name = duty_name
                aa.pmobile = mobile
                aa.pdescription = description
                aa.save()
                data = {
                    "status": 1,
                    "message": u"修改用户信息成功",
                    "data": []
                }
            except Exception as e:
                data = {
                    "status": 0,
                    "message": u"修改用户信息失败",
                    "data": []
                }
        else:
            try:
                row2 = MySQLDB.SelectMySql(
                    "SELECT 1 FROM `t_sys_user` where login_name ='%s' and status=1 and user_id=%s;" % (
                        login_name, user_id))
                try:
                    flag2 = row2[0][0]
                except:
                    flag2 = 0
                if flag2 == 1:
                    row = MySQLDB.CommitMySql(
                        "UPDATE t_sys_user set description = '%s',sex = '%s',real_name = '%s',birthday = '%s',organize_id = '%s',organize_name = '%s',dept_id = '%s',dept_name = '%s',duty_name = '%s',role_id = '%s',mobile = '%s',email = '%s' where user_id= '%s';" % (
                            description, sex, real_name, birthday, organize_id, organize_name, dept_id, dept_name,
                            duty_name, role_id, mobile, email, user_id))
                    aa = Person.objects.get(puserid=user_id)
                    dd = User.objects.get(last_name=aa.puser.last_name)
                    dd.last_name = real_name
                    dd.email = email
                    dd.username = login_name
                    dd.save()
                    aa.prole_id = role_id
                    aa.psex = sex
                    aa.pbirthday = birthday
                    aa.porganize_id = organize_id
                    aa.porganize_name = organize_name
                    aa.pdept_id = dept_id
                    aa.pdept_name = dept_name
                    aa.pduty_name = duty_name
                    aa.pmobile = mobile
                    aa.pdescription = description
                    aa.save()
                    data = {
                        "status": 1,
                        "message": u"修改用户信息成功",
                        "data": []
                    }
                else:
                    data = {
                        "status": 0,
                        "message": u"该登录名已存在",
                        "data": []
                    }
            except Exception as e:
                data = {
                    "status": 0,
                    "message": u"查询是否存在登陆名失败1",
                    "data": []
                }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查询是否存在登陆名失败",
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：删除用户信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_YHGL_3(request):
    user_id = request.GET['user_id']  # POST请求获取html传过来的参数
    try:
        b0 = MySQLDB.CommitMySql("update t_sys_user set status = 0 where user_id = '%s';" % (user_id))
        a = Person.objects.get(puserid=user_id)
        Person.objects.get(puserid=user_id).delete()
        User.objects.get(last_name=a.puser.last_name).delete()
        data = {
            "status": 1,
            "message": u"删除用户信息成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：重置用户密码信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_YHGL_4(request):
    user_id = request.GET['user_id']  # POST请求获取html传过来的参数
    try:
        b0 = MySQLDB.CommitMySql(
            "update t_sys_user set password = 'e10adc3949ba59abbe56e057f20f883e' where user_id = '%s';" % (user_id))
        row3 = MySQLDB.SelectMySql( "SELECT login_name FROM `t_sys_user` where user_id ='%s';" % (user_id))
        user = User.objects.get(username=row3[0][0])
        # user = User.objects.get(username=user_id)
        if user is not None:
            defaultpwd = "123456"
            user.set_password(defaultpwd)
            user.save()
        data = {
            "status": 1,
            "message": u"重置用户密码成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：新增用户信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_YHGL_5(request):
    login_name = request.POST['login_name']  # 账号
    xrole_id = request.POST['role_id']  # 角色ID
    role_id = int(xrole_id)
    real_name = request.POST['real_name']  # 姓名
    xsex = request.POST['sex']  # 性别
    sex = int(xsex)
    birthday = request.POST['birthday']  # 生日
    xorganize_id = request.POST['organize_id']  # 单位ID
    organize_id = int(xorganize_id)
    organize_name = request.POST['organize_name']  # 单位名称
    xdept_id = request.POST['dept_id']  # 部门ID
    dept_id = int(xdept_id)
    dept_name = request.POST['dept_name']  # 部门名称
    duty_name = request.POST['duty_name']  # 职务名称
    mobile = request.POST['mobile']  # 电话
    email = request.POST['email']  # 邮箱
    passwd = "e10adc3949ba59abbe56e057f20f883e"  # 初始密码 123456
    description = request.POST['description']
    status = 1
    is_external = 0
    try:
        row1 = MySQLDB.SelectMySql("SELECT 1 FROM `t_sys_user` where login_name ='%s' and status=1;" % (login_name))
        try:
            flag = row1[0][0]
        except:
            flag = 0
        filterResult = User.objects.filter(username=login_name)
        if len(filterResult) != 0:
            flag = 1
        if flag != 1:
            try:
                b1 = MySQLDB.CommitMySql(
                    "INSERT INTO t_sys_user (description,login_name,password,sex,real_name,organize_id,organize_name,dept_id,dept_name,duty_name,role_id,email,mobile,birthday,status,is_external) VALUES ('%s','%s','%s',%s,'%s',%s,'%s',%s,'%s','%s',%s,'%s','%s','%s',%s,%s);" % (
                        description, login_name, passwd, sex, real_name, organize_id, organize_name, dept_id, dept_name,
                        duty_name, role_id, email, mobile, birthday, status, is_external))

                # 新增用户
                row2 = MySQLDB.SelectMySql(
                    "SELECT user_id FROM `t_sys_user` where login_name ='%s' and status=1;" % (login_name))
                new_userid = row2[0][0]
                user = User.objects.create_user(username=login_name, email=email, password="123456")
                user.first_name = dept_name
                user.last_name = real_name
                user.save()
                puser = Person.objects.create(puser=user,
                                              puserid=new_userid,
                                              psex=sex,
                                              pbirthday=birthday,
                                              porganize_id=organize_id,
                                              porganize_name=organize_name,
                                              pdept_id=dept_id,
                                              pdept_name=dept_name,
                                              pduty_name=duty_name,
                                              pmobile=mobile,
                                              pdescription=description,
                                              pstatue=status,
                                              pis_external=is_external)
                puser.save()
                data = {
                    "status": 1,
                    "message": u"新增用户信息成功",
                    "data": []
                }
            except Exception as e:
                data = {
                    "status": 0,
                    "message": u"新增用户信息失败",
                    "data": []
                }
        else:
            data = {
                "status": 0,
                "message": u"登陆名已存在",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查询登录名是否存在失败",
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


######################
# 个人中心方法
######################

# 功能：修改密码
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_GRZX_2(request):
    xuser_id = request.COOKIES["userid"]
    user_id = int(xuser_id)
    password = request.GET['password']
    newpassword = request.GET['newpassword']
    password2 = request.GET['password2']
    try:
        row = MySQLDB.SelectMySql(
            "SELECT 1 FROM `t_sys_user` where user_id ='%s' and status=1 and password='%s';" % (user_id, password))
        try:
            flag = row[0][0]
        except:
            flag = 0
        if flag == 1:
            try:
                b0 = MySQLDB.CommitMySql(
                    "UPDATE t_sys_user set password = '%s' where user_id = '%s'and status=1;" % (newpassword, user_id))
                row3 = MySQLDB.SelectMySql( "SELECT login_name FROM `t_sys_user` where user_id ='%s';" % (user_id))
                user = User.objects.get(username=row3[0][0])
                if user is not None:
                    user.set_password(password2)
                    user.save()
                data = {
                    "status": 1,
                    "message": u"修改成功",
                    "data": []
                }
            except Exception as e:
                data = {
                    "status": 0,
                    "message": u"修改密码失败",
                    "data": []
                }
        else:
            data = {
                "status": 0,
                "message": u"原密码不相符",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"验证原密码失败",
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：修改用户信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_GRZX_3(request):
    user_id = request.COOKIES["userid"]
    uid = int(user_id)
    xsex = request.GET['sex']
    sex = int(xsex)
    real_name = request.GET['real_name']
    birthday = request.GET['birthday']
    mobile = request.GET['mobile']
    email = request.GET['email']
    try:
        row = MySQLDB.CommitMySql(
            "UPDATE t_sys_user set sex = '%s',real_name = '%s',birthday = '%s',mobile = '%s',email = '%s' where user_id= '%s';" % (
                sex, real_name, birthday, mobile, email, uid))
        data = {
            "status": 1,
            "message": u"修改用户信息成功",
            "data": []
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


######################
# 通讯录方法
######################
# 功能：获取通讯录信息
# 输入参数：request
# 返回参数：response
@authjson
def XTGL_TXL_1(request):
    alist = []
    try:
        row = MySQLDB.SelectMySql(
            "select real_name,organize_name,duty_name,mobile,email,description from t_sys_user where status=1;")
        if len(row) > 0:
            key = ["real_name", "organize_name", "duty_name", "mobile", "email", "description"]
            for i in range(len(row)):
                info = {}
                for j in range(len(key)):
                    info[key[j]] = row[i][j]
                alist.append(info)
        data = {
            "status": 1,
            "message": u"查询成功",
            "data": alist
        }
    except Exception as e:
        data = {
            "status": 0,
            "message": u"查询失败",
            "data": []
        }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


def XTGL_BMGL_ADDSAVE(request):
    deptname = request.POST.get('unitname', '')
    address = request.POST.get('address', 0)
    parent_id = request.POST.get('parent_id', 0)
    tel = request.POST.get('tel', 0)
    desc = request.POST.get('jobdescription', 0)
    header = request.POST['header']
    try:
        # 验证部门名称是否重复
        selectsql = "select 1 from t_sys_organize where name = '%s' and status=1;" % deptname
        valid = MySQLDB.SelectMySql(selectsql)
        if len(valid) > 0:
            raise Exception("部门名称重复，请重新输入")
        # 验证上级部门是否存在
        if int(parent_id) == -99:  # 建立公司
            insertsql = "INSERT INTO t_sys_organize (status,name,address,manager,tel,description,category) VALUES (1,'%s','%s','%s','%s','%s',1);" % (
                deptname, address, header, tel, desc)
        else:
            selectsql = "select name from t_sys_organize where organize_id = %s;" % parent_id
            valid = MySQLDB.SelectMySql(selectsql)
            if len(valid) < 1:
                raise Exception("上级单位不存在，请重新选择")
            else:
                parentName = valid[0][0]
            insertsql = "INSERT INTO t_sys_organize (status,name,parent_id,parent_name,address,manager,tel,description,category) VALUES (1,'%s',%s,'%s','%s','%s','%s','%s',2);" % (
                deptname, parent_id, parentName, address, header, tel, desc)
        row = MySQLDB.CommitMySql(insertsql)
        if row != 'ok':
            raise Exception(row)
        row4 = MySQLDB.SelectMySql(
                "select organize_id from t_sys_organize where name = '%s' and status=1;" % deptname)
        new_organizeid = row4[0][0]
        Company.objects.create(cname=deptname,
                               corganize_id=new_organizeid,
                               cpatent_id=parent_id,
                               cpatent_name=parentName,
                               caddress=address,
                               cmanager=header,
                               ctel=tel,
                               cdesctiption=desc)
        data = dict(status=1, message="新增成功", data=[])
    except Exception as e:
        data = dict(status=0, message=str(e), data=[])
    return JsonResponse(data)
